package com.dmcloud.zuul.config;

import com.dmcloud.common.util.reponse.ResponseConstant;
import com.dmcloud.common.util.reponse.ResultMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.http.AccessTokenRequiredException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiaodao
 * date: 2020/3/29
 * 认证过程中直接抛出异常
 */
@Component
@Slf4j
public class GatewayAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        request.setAttribute("updateLog","yes");
        if(e instanceof AccessTokenRequiredException){
            log.info("未登录访问"+request.getRequestURI());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");

            String json = objectMapper.writeValueAsString(ResultMessage.errorMsg(ResponseConstant.UN_AUTHENTICATION,"请登录后再访问！"));
            response.getWriter().write(json);
            response.getWriter().flush();
         log.info("401 没有传令牌");
        }else {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");
            String json = objectMapper.writeValueAsString(ResultMessage.errorMsg(ResponseConstant.UN_AUTHENTICATION,"令牌校验失败！"));
            response.getWriter().write(json);
            response.getWriter().flush();
            log.info("401 令牌校验失败");
        }



//        super.commence(request,httpServletResponse,e);
    }
}
